<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人中心</span>
        </div>
      </template>

      <div class="profile-content">
        <!-- 头像上传区域 -->
        <div class="avatar-section">
          <div class="avatar-upload">
            <el-avatar 
              :size="120" 
              :src="userInfo.avatar || defaultAvatar"
              class="avatar"
            />
            <div class="avatar-actions">
              <el-upload
                class="avatar-uploader"
                action="/api/profile/upload-avatar"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
              >
                <el-button type="primary" size="small">更换头像</el-button>
              </el-upload>
              <el-button 
                size="small" 
                @click="resetAvatar"
                :disabled="!userInfo.avatar"
              >
                恢复默认
              </el-button>
            </div>
          </div>
        </div>

        <!-- 个人信息表单 -->
        <div class="info-section">
          <el-form
            ref="infoFormRef"
            :model="userInfo"
            :rules="infoRules"
            label-width="100px"
            class="info-form"
          >
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userInfo.name" placeholder="请输入姓名" />
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userInfo.phone" placeholder="请输入手机号" />
            </el-form-item>

            <el-form-item label="角色">
              <el-tag :type="getRoleTagType(userInfo.role)">
                {{ getRoleText(userInfo.role) }}
              </el-tag>
            </el-form-item>

            <el-form-item label="注册时间">
              <span>{{ userInfo.createTime || '未知' }}</span>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="updateInfo" :loading="infoLoading">
                保存信息
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>

    <!-- 修改密码卡片 -->
    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>

      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
        class="password-form"
      >
        <el-form-item label="原密码" prop="oldPwd">
          <el-input 
            type="password" 
            v-model="passwordForm.oldPwd" 
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPwd">
          <el-input 
            type="password" 
            v-model="passwordForm.newPwd" 
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPwd">
          <el-input 
            type="password" 
            v-model="passwordForm.confirmPwd" 
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="changePassword" :loading="passwordLoading">
            修改密码
          </el-button>
          <el-button @click="resetPasswordForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/api/axios'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

// 默认头像
const defaultAvatar = '/avatars/default-avatar.png'

// 响应式数据
const userInfo = reactive({
  id: '',
  name: '',
  phone: '',
  role: '',
  avatar: '',
  createTime: ''
})

const passwordForm = reactive({
  oldPwd: '',
  newPwd: '',
  confirmPwd: ''
})

const infoFormRef = ref()
const passwordFormRef = ref()
const infoLoading = ref(false)
const passwordLoading = ref(false)

// 表单验证规则
const infoRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPwd: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPwd) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 角色标签类型
const getRoleTagType = (role) => {
  const types = {
    'caregiver': 'success',
    'admin': 'danger',
    'reception': 'warning',
    'family': 'info'
  }
  return types[role] || 'info'
}

// 角色文本
const getRoleText = (role) => {
  const texts = {
    'caregiver': '护工',
    'admin': '管理员',
    'reception': '前台',
    'family': '家属'
  }
  return texts[role] || '未知'
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const response = await axios.get('/profile/info')
    Object.assign(userInfo, response.data)
  } catch (error) {
    console.error('加载用户信息失败:', error)
    ElMessage.error('加载用户信息失败')
  }
}

// 更新个人信息
const updateInfo = async () => {
  try {
    await infoFormRef.value.validate()
    infoLoading.value = true
    
    const updateData = {
      role: userInfo.role,
      userId: userInfo.id,
      name: userInfo.name,
      phone: userInfo.phone
    }
    
    await axios.post('/profile/update-info', updateData)
    ElMessage.success('个人信息更新成功')
    
    // 更新store中的用户信息
    userStore.updateUserInfo({
      name: userInfo.name,
      phone: userInfo.phone
    })
  } catch (error) {
    console.error('更新个人信息失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('个人信息更新失败')
    }
  } finally {
    infoLoading.value = false
  }
}

// 修改密码
const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true
    
    const passwordData = {
      oldPwd: passwordForm.oldPwd,
      newPwd: passwordForm.newPwd
    }
    
    await axios.post('/auth/changePwd', passwordData)
    ElMessage.success('密码修改成功')
    resetPasswordForm()
  } catch (error) {
    console.error('修改密码失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('密码修改失败')
    }
  } finally {
    passwordLoading.value = false
  }
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.oldPwd = ''
  passwordForm.newPwd = ''
  passwordForm.confirmPwd = ''
  passwordFormRef.value?.clearValidate()
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

// 头像上传成功
const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    userInfo.avatar = response.data
    ElMessage.success('头像上传成功')
    
    // 更新store中的头像
    userStore.updateUserInfo({
      avatar: userInfo.avatar
    })
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 头像上传失败
const handleAvatarError = () => {
  ElMessage.error('头像上传失败')
}

// 恢复默认头像
const resetAvatar = async () => {
  try {
    await ElMessageBox.confirm('确定要恢复默认头像吗？', '提示', {
      type: 'warning'
    })
    
    await axios.post('/profile/reset-avatar', {
      role: userInfo.role,
      userId: userInfo.id
    })
    
    userInfo.avatar = ''
    ElMessage.success('头像已恢复默认')
    
    // 更新store中的头像
    userStore.updateUserInfo({
      avatar: ''
    })
  } catch (error) {
    if (error !== 'cancel') {
      console.error('恢复默认头像失败:', error)
      ElMessage.error('恢复默认头像失败')
    }
  }
}

// 组件挂载时加载用户信息
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card,
.password-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-content {
  display: flex;
  gap: 40px;
  align-items: flex-start;
}

.avatar-section {
  flex-shrink: 0;
}

.avatar-upload {
  text-align: center;
}

.avatar {
  margin-bottom: 16px;
  border: 2px solid #f0f0f0;
}

.avatar-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-section {
  flex: 1;
}

.info-form,
.password-form {
  max-width: 400px;
}

@media (max-width: 768px) {
  .profile-content {
    flex-direction: column;
    gap: 20px;
  }
  
  .info-form,
  .password-form {
    max-width: 100%;
  }
}
</style>
